import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart'; //提示
import 'dart:convert'; //格式转换
import 'package:dio/dio.dart';//异步请求
import '../config/SystemConfig.dart';
import '../util/Storage.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {


  //控件手机号码文本框控制器
  TextEditingController _tel = new TextEditingController();
  //密码控制器
  TextEditingController _pwd = new TextEditingController();
  //异步登录
  void _login() async {
    String api = SystemConfig.BASE_URL + "/appUser/login";
    print(api);
    Response response = await Dio() //响应，response服务器响应
        .post(api, queryParameters: {
      "mobile": '${this._tel.text}',
      'pwd': '${this._pwd.text}' 
    });
    //post发送http请求,敏感数据//http请求响应的状态码
    print(response.statusCode);
    print(response.toString());
    Map result = json.decode(response.toString()); //json解码
    //判断登录是否成功
    if (response.statusCode == 200 && result != null && result['success']) {
      this._tel.text = "";
      this._pwd.text = "";
      //200请求响应成功，404服务端没有，找不到资源，500服务端问题
      //将用户信息保存到本地存储器中
      Storage.setString(
          'userInfo', json.encode(result['data'])); //字符串类型，用json.encode编码成字符串
      Navigator.pushReplacementNamed(context, '/tabs');//跳转到广场首页
    } else {
      print(response.statusCode);
      print('登陆失败');
      this._pwd.text = "";
      Fluttertoast.showToast(
          //登陆失败弹出小提示
          msg: '用户名和密码错误',
          backgroundColor: Colors.black87,
          gravity: ToastGravity.CENTER, //
          toastLength: Toast.LENGTH_LONG, //提示时间很长
          textColor: Colors.red,
          fontSize: 20.0);
      // Fluttertoast.showToast(msg: result['']);

    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: new EdgeInsets.all(20.0),
        child: ListView(
          //listview 无状态
          //登录框上拉，自由滑动的组件，带有上下滑动，用的多的话，触发事件多，开销大，加载慢
          children: <Widget>[
            SizedBox(height: 20.0),
            Center(
              child: Container(
                width: 120.0,
                height: 120.0,
                child: ClipOval(
                  //图片的组件,显示圆形的图片
                  child: Image.asset("images/logo.png", fit: BoxFit.cover),
                ),
              ),
            ),
            //手机号码输入框
            Container(
              margin: EdgeInsets.only(bottom: 20.0),
              child: TextField(
                keyboardType: TextInputType.number,
                cursorColor: Colors.orangeAccent,
                decoration: InputDecoration(hintText: '请输入手机号码'),
                onChanged: (value) {
                  //文本改变事件，每次输入的内容就会赋值给文本控制器
                  this._tel.text = value;
                  //改变文本框光标焦点位置，默认用了控制器后，光标的位置始终在前面R
                  this._tel.selection = TextSelection.fromPosition(
                      TextPosition(offset: this._tel.text.length));
                },
              ),
            ),

            //密码输入框
            Container(
              margin: EdgeInsets.only(bottom: 20.0),
              child: TextField(
                obscureText: true,
                cursorColor: Colors.orangeAccent,
                decoration: InputDecoration(hintText: '请输入密码'),
                onChanged: (value) {
                  //文本改变事件，每次输入的内容就会赋值给文本控制器
                  this._pwd.text = value;
                },
              ),
            ),

            //忘记密码，新用户注册
            Container(
              margin: EdgeInsets.only(bottom: 20.0),
              padding: EdgeInsets.only(left: 10.0, right: 10.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  // //text没有点击事件
                  // Text('忘记密码'),
                  // Text('请注册')
                  // 所有加上点击事件的组件只要在InkWell
                  InkWell(
                    child: Text('忘记密码',
                    style: TextStyle(color:Colors.black87,fontSize: 18.0),),
                    onTap: () {},
                  ),
                  InkWell(
                    child: Text(
                      '新用户注册',
                      style: TextStyle(color:Colors.black87,fontSize: 18.0),),
                    onTap: () {
                      Navigator.pushNamed(context, '/register');
                    },
                  )
                ],
              ),
            ),

            //登录按钮
            RaisedButton(
              child: Text(
                '登录',
                style: TextStyle(color: Colors.white, fontSize: 16.0),
              ),
              color: Colors.blue[300],

              //事件为null禁用
              onPressed: () {
                //登录成功，进入首页
                // Navigator.pushNamed(context, '/tabs');
                // Navigator.pushReplacementNamed(context, '/tabs');
                this._login();
              },
              shape: new RoundedRectangleBorder(
                  //设置为圆角
                  borderRadius: BorderRadius.circular(20),
                  //无边框
                  side: BorderSide.none),
            )
          ],
        ),
      ),
    );
  }
}
